import React from 'react';
import { inject, observer } from 'mobx-react';
import { Spin, Button, Icon, Modal, Table } from 'antd';
import { WeaBrowser, WeaPopoverHrm, WeaInput, WeaSlideModal, WeaTop, WeaRightMenu, WeaLocaleProvider } from 'ecCom';
import SearchCondition from '../../public/base/SearchCondition';
import KnowledgeMapEdit from './KnowledgeMapEdit';

const getLabel = WeaLocaleProvider.getLabel;
const toJS = mobx.toJS;


@inject('KnowledgeMapListStore')
@observer
export default class KnowledgeMapList extends React.Component {
    constructor(props) {
        super(props);
        window.develop = '知识地图维护';
        this.state = {
            refeshid: -1,
            heightInit: false,
            _top: 0,
            content: '',
            tableloading: false,
            searchStatus: false,
            height: this.getHeight(),
            pageSize: '',
            topName: getLabel(27939, '知识地图') + getLabel(320, '维护'),
            isshowleft: true,
            locationkey: new Date().getTime(),
            field: '',
            order: '',
            menu: [
                {
                    key: '0',
                    icon: <i className="icon-coms-search" />,
                    content: getLabel(197, '搜索'),
                    onClick: key => this.advanceSearch(),
                },
                {
                    key: '1',
                    icon: <i className="icon-coms-Reset" />,
                    content: getLabel(27088, '重置'),
                    onClick: key => this.resetSearch(),
                }, {
                    key: '2',
                    icon: <i className="icon-coms-Approval" />,
                    content: getLabel(82, '新建'),
                    onClick: key => this.newKnowledge(),
                },
            ],
            columns: [
                {
                    title: getLabel(27939, '知识地图') + getLabel(195, '名称'),
                    width: '*',
                    dataIndex: 'name',
                    sorter: true,
                    render: (text, record, index) =>
                        <div style={{ cursor: 'pointer' }} onClick={e => this.getClickDetail(e, record, 'view')}>{text}</div>,
                }, {
                    title: getLabel(882, '创建人'),
                    width: '10%',
                    dataIndex: 'createrName',
                    render: (text, record, index) => <a href="javaScript:void(0)" onClick={(e) => {
                        openhrm(record.createrId); window.pointerXY(e);
                    }} title={text} >{text}</a>,
                }, {
                    title: getLabel(1339, '创建时间'),
                    width: '15%',
                    dataIndex: 'createDate',
                    sorter: true,
                    render: (text, record, index) => <div className="noWrap" title={text}>{text}</div>,
                }, {
                    title: getLabel(3002, '最后修改人'),
                    width: '10%',
                    dataIndex: 'updaterName',
                    render: (text, record, index) => <a href="javaScript:void(0)" onClick={(e) => {
                        openhrm(record.updaterId); window.pointerXY(e);
                    }} title={text} >{text}</a>,
                }, {
                    title: getLabel(19521, '最后修改日期'),
                    width: '15%',
                    dataIndex: 'updateDate',
                    sorter: true,
                    render: (text, record, index) => <div className="noWrap" title={text}>{text}</div>,
                }, {
                    title: getLabel(104, '操作'),
                    width: '20%',
                    dataIndex: 'rowid',
                    className: 'normalfiled',
                    render: (text, record, index) =>
                        (<div className="coustmerStyle">
                            <span className="distribute" onClick={e => this.handleMenuClick(e, record, '1')}>编辑</span>
                            <span className="distribute" onClick={e => this.handleMenuClick(e, record, '2')}>删除</span>
                            <span className="distribute" onClick={e => this.handleMenuClick(e, record, '3')}>进入</span>
                            <span className="distribute" onClick={e => this.handleMenuClick(e, record, '4')}>添加菜单</span>
                            <span className="distribute" onClick={e => this.handleMenuClick(e, record, '5')}>URL</span>
                        </div>),
                },
            ],
            
        };
    }

    componentWillMount() { // 一些初始化请求
        const { KnowledgeMapListStore } = this.props;
        let { columns, menu } = this.state;
        let _this = this;
        KnowledgeMapListStore.getKnowledgeList({
            doback(hasRight, hasaddmenu) {
                if (!hasRight) {
                    menu = menu.splice(0, 2);
                    if (hasaddmenu) {
                        columns[5] = {
                            title: getLabel(104, '操作'),
                            width: '20%',
                            dataIndex: 'rowid',
                            className: 'normalfiled',
                            render: (text, record, index) =>
                                (<div className="coustmerStyle">
                                    <span className="distribute" onClick={e => _this.handleMenuClick(e, record, '3')}>进入</span>
                                    <span className="distribute" onClick={e => _this.handleMenuClick(e, record, '4')}>添加菜单</span>
                                    <span className="distribute" onClick={e => _this.handleMenuClick(e, record, '5')}>URL</span>
                                </div>),
                        };
                    } else {
                        columns[5] = {
                            title: getLabel(104, '操作'),
                            width: '20%',
                            dataIndex: 'rowid',
                            className: 'normalfiled',
                            render: (text, record, index) =>
                                (<div className="coustmerStyle">
                                    <span className="distribute" onClick={e => _this.handleMenuClick(e, record, '3')}>进入</span>
                                    <span className="distribute" onClick={e => _this.handleMenuClick(e, record, '5')}>URL</span>
                                </div>),
                        };
                    }
                    _this.setState({ columns, menu });
                } else {
                    if (!hasaddmenu) {
                        columns[5] = {
                            title: getLabel(104, '操作'),
                            width: '20%',
                            dataIndex: 'rowid',
                            className: 'normalfiled',
                            render: (text, record, index) =>
                                (<div className="coustmerStyle">
                                    <span className="distribute" onClick={e => _this.handleMenuClick(e, record, '1')}>编辑</span>
                                    <span className="distribute" onClick={e => _this.handleMenuClick(e, record, '2')}>删除</span>
                                    <span className="distribute" onClick={e => _this.handleMenuClick(e, record, '3')}>进入</span>
                                    <span className="distribute" onClick={e => _this.handleMenuClick(e, record, '5')}>URL</span>
                                </div>),
                        };
                    }
                    _this.setState({ columns, menu });
                }
            },
        });
    }
    componentWillUnmount() {
        this.onCloseSlideModal();
    }
    // 点击菜单
    handleMenuClick=(e, record, type)=> {
        const { KnowledgeMapListStore } = this.props;
        let { hasRight, hasaddmenu } = KnowledgeMapListStore;
        let rowid = record.rowid;
        KnowledgeMapListStore.rowid = record.rowid;
        if (!hasRight && (type == '1' || type == '2')) {
            e.stopPropagation();
            e.nativeEvent.stopImmediatePropagation();
            return;
        }
        if (!hasaddmenu && type == '4') {
            e.stopPropagation();
            e.nativeEvent.stopImmediatePropagation();
            return;
        }
        if (type == '1') { // 编辑
            this.getClickDetail(e, record, 'edit');
        } else if (type == '2') { // 删除
            this.doDelete(e, record);
        } else if (type == '3') { // 进入
            window.open(`/knowledgeMap/data/MainInfo.jsp?mapId=${rowid}`);
        } else if (type == '4') { // 添加菜单
            console.log('111');
            window.open('/wui/engine.html#/portalengine/portalmenu/custommenu');
        } else if (type == '5') { // url
            window.prompt('地址', `${location.protocol}//${location.host}/knowledgeMap/data/MainInfo.jsp?mapId=${rowid}`);
        }
    }
    // 删除
    doDelete=(e, record)=> {
        const { KnowledgeMapListStore } = this.props;
        let _this = this;
        Modal.confirm({
            title: '确定要删除吗？',
            onOk() {
                KnowledgeMapListStore.operateKnowledge({
                    operation: 'delete',
                    knowledgeId: record.rowid,
                    doback(status) {
                        if (status == '1') {
                            KnowledgeMapListStore.getKnowledgeList();
                        } else if (status == '3') {
                            Modal.error({
                                title: '提示',
                                content: '知识点被引用,不能删除!',
                            });
                        }
                    },
                });
            },
            onCancel() {

            },
        });
        e.stopPropagation();
        e.nativeEvent.stopImmediatePropagation();
    }
    onCancelDia=(type, value)=> {
        if (type == 1) {
            const { KnowledgeMapListStore } = this.props;
            let _this = this;
            Modal.confirm({
                title: '确定要删除吗？',
                onOk() {
                    KnowledgeMapListStore.operateKnowledge({
                        operation: 'delete',
                        knowledgeId: value,
                        doback(status) {
                            if (status == '1') {
                                KnowledgeMapListStore.getKnowledgeList();
                                _this.onCloseSlideModal();
                            }
                        },
                    });
                },
                onCancel() {

                },
            });
        } else {
            this.onCloseSlideModal();
        }
    }
    getHeight(header) {
        let h = 0;
        if (header) {
            h = header.clientHeight || 0;
            if (document.getElementsByClassName('e9theme-layout2-navbar')[0]) {
                h = h * 2 + 10;
            }
        }
        return window.innerHeight - h;
    }

    getTopHeight(header) {
        let h = 0;
        if (header) {
            h = header.clientHeight || 0;
            if (document.getElementsByClassName('e9theme-layout2-navbar')[0]) {
                h = h * 2 + 10;
            }
        }
        return h;
    }

    // 知识点名称 创建人
    onBaseSearchChange = (ids, names, datas, type, typeArray) => {
        const { KnowledgeMapListStore } = this.props;
        if (typeArray != '') {
            KnowledgeMapListStore[typeArray] = datas;
        }
        KnowledgeMapListStore[type] = ids;
    }

    advanceSearch = () => {
        const { KnowledgeMapListStore } = this.props;
        this.setState({ searchStatus: true });
        let searchParams = this.pieceSearchParam('', '', 'buttonSearch');
        KnowledgeMapListStore.getKnowledgeList(searchParams);
    }
    // 重置
    resetSearch = () => {
        const { KnowledgeMapListStore } = this.props;
        KnowledgeMapListStore.createrArray = [];
        KnowledgeMapListStore.createrId = '';
        KnowledgeMapListStore.name = '';
        this.setState({ searchStatus: false, pageSize: 20 });
    }
    getTabButtonsAd = () => {
        const { KnowledgeMapListStore } = this.props;
        let { hasRight } = KnowledgeMapListStore;
        let button = [(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pcz9zk@search`} type="primary" onClick={this.advanceSearch}>{getLabel(197, '搜索')}</Button>),
        (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@hpztcm@reset`} type="ghost" onClick={this.resetSearch}>{getLabel(27088, '重置')}</Button>),
        ];
        return button;
    }
    getLeftItems = (refesh) => {
        const { KnowledgeMapListStore } = this.props;
        const { name, createrId, createrArray } = KnowledgeMapListStore;
        return [
            {
                title: getLabel(27939, '知识地图') + getLabel(195, '名称'), btn: <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@xfkhuv@knowledgeMapName`} style={{ width: 250 }} onPressEnter={(e) => {
                    this.advanceSearch();
                }} placeholder={getLabel(27939, '知识地图') + getLabel(195, '名称')} value={name} onChange={val => this.onBaseSearchChange(val, '', '', 'name', '')} />
            },
            { title: getLabel(882, '创建人'), btn: <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@s42d0p@$knowledgeMapCreater`} placeholder={getLabel(882, '创建人')} inputStyle={{ width: 250 }} type={17} replaceDatas={createrArray} onChange={(ids, names, datas) => this.onBaseSearchChange(ids, names, datas, 'createrId', 'createrArray')} isSingle={false} /> },
        ];
    }
    showTotal(total) {
        return `共 ${total} 条`;
    }
    showCurrentChange = (current) => {
        const { KnowledgeMapListStore } = this.props;
        KnowledgeMapListStore.pageNum = current;
        let searchParams = this.pieceSearchParam(current, this.state.pageSize);
        KnowledgeMapListStore.getKnowledgeList(searchParams);
    }
    onShowSizeChange = (current, pageSize) => {
        const { KnowledgeMapListStore } = this.props;
        this.setState({ pageSize });
        KnowledgeMapListStore.pageNum = current;
        let searchParams = this.pieceSearchParam(current, pageSize);
        KnowledgeMapListStore.getKnowledgeList(searchParams);
    }
    // 返回查询条件
    pieceSearchParam = (current, pageSize, type) => {
        const { KnowledgeMapListStore } = this.props;
        let searchParams = {};
        if (type == 'buttonSearch') {
            searchParams = {
                name: KnowledgeMapListStore.name,
                createrId: KnowledgeMapListStore.createrId,
                field: this.state.field,
                order: this.state.order,
            };
        } else if (this.state.searchStatus) {
            searchParams = {
                pageNum: current,
                pageSize,
                name: KnowledgeMapListStore.name,
                createrId: KnowledgeMapListStore.createrId,
                field: this.state.field,
                order: this.state.order,
            };
        } else {
            searchParams = {
                pageNum: current,
                pageSize,
                field: this.state.field,
                order: this.state.order,
            };
        }
        return searchParams;
    }

    // 打开新增页面
    newKnowledge = (e) => {
        const { KnowledgeMapListStore } = this.props;
        const { _top } = this.state;
        KnowledgeMapListStore.slidevisible = true;
        this.setState({ locationkey: new Date().getTime() });
        this.setState({ content: <KnowledgeMapEdit ecId={`${this && this.props && this.props.ecId || ''}_KnowledgeMapEdit@jhh68e`} onCallBackSuccess={this.onCallBackSuccess} onCancelDia={this.onCancelDia} minusHeight={_top} operation="add" /> });
        if (e) {
            e.stopPropagation();
            e.nativeEvent.stopImmediatePropagation();
        }
    }
    // 点击名称弹出Detail
    getClickDetail = (e, record, type) => {
        const { KnowledgeMapListStore } = this.props;
        const { _top } = this.state;
        KnowledgeMapListStore.slidevisible = true;
        let _refeshid = -1;
        if (this.state.refeshid == -1) {
            _refeshid = 0;
        }
        this.setState({ content: <KnowledgeMapEdit ecId={`${this && this.props && this.props.ecId || ''}_KnowledgeMapEdit@zuv5ue`} knowledgeId={record.rowid} refeshid={_refeshid} onCancelDia={this.onCancelDia} onCallBackSuccess={this.onCallBackSuccess} operation={type} minusHeight={_top} />, refeshid: _refeshid });
        e.stopPropagation();
        e.nativeEvent.stopImmediatePropagation();
    }
    // 隐藏detail
    hideDetail = (e) => {
        const { KnowledgeMapListStore } = this.props;
        if (KnowledgeMapListStore.slidevisible) {
            KnowledgeMapListStore.slidevisible = false;
        }
    }
    // 操作完成回调
    onCallBackSuccess = (optparams) => {
        this.setState({ tableloading: true });
        const { KnowledgeMapListStore } = this.props;
        if (optparams.opttype == 'add') {
            this.onCloseSlideModal();
            KnowledgeMapListStore.getKnowledgeList({});
            this.setState({ tableloading: false });
        }
        if (optparams.opttype == 'edit') {
            let rowid = optparams.rowid;
            let type = optparams.type;
            let value = optparams.value;
            let dataSource = KnowledgeMapListStore.dataSource;
            dataSource.length > 0 && dataSource.map((element, index) => {
                if (element.rowid == rowid) {
                    for (let i = 0; i < type.length; i++) {
                        element[type[i]] = value[i];
                    }
                }
            });
            KnowledgeMapListStore.dataSource = dataSource;
            this.setState({ tableloading: false });
        }
    }

    // 关闭侧拉框
    onCloseSlideModal=()=> {
        const { KnowledgeMapListStore } = this.props;
        KnowledgeMapListStore.slidevisible = false;
    }

    // 左右布局按钮点击事件
    leftRightFun=(leftShow)=> {
        this.setState({ isshowleft: leftShow });
    }

    ontableChange = (pagination, filters, sorter) => {
        let { field, order } = this.state;
        if (sorter.field != field || sorter.order != order) {
            const { KnowledgeMapListStore } = this.props;
            let searchParams = this.pieceSearchParam('', '', 'buttonSearch');
            searchParams.field = sorter.field;
            searchParams.order = sorter.order;
            KnowledgeMapListStore.getKnowledgeList(searchParams);
            this.setState({ field: sorter.field, order: sorter.order });
        }
    }


    getDetail=()=> {
        const { KnowledgeMapListStore } = this.props;
        let { height, tableloading, columns } = this.state;
        let { dataSource, itotal, pageNum } = KnowledgeMapListStore;

        return (
            <div className="main-tablist">
                <Table ecId={`${this && this.props && this.props.ecId || ''}_Table@u7geag`}
                    scroll={{ x: window.innerWidth * 0.6, y: height - 220 }}
                    columns={columns}
                    bordered={false}
                    loading={tableloading}
                    className="wea-develop-antd-table"
                    onChange={this.ontableChange}
                    dataSource={dataSource}
                    pagination={{
                        total: itotal,
                        onChange: this.showCurrentChange,
                        showTotal: this.showTotal,
                        defaultPageSize: '20',
                        current: pageNum,
                        showSizeChanger: true,
                        onShowSizeChange: this.onShowSizeChange,
                    }}
                />
            </div>
        );
    }
    getTopBtns=()=>{
        const {hasRight}=this.props.KnowledgeMapListStore;
        return [
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1gpyy1@search_top`} type="primary" onClick={this.advanceSearch} >{getLabel(197, '搜索')}</Button>,
        hasRight && <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vtolk7@createKnowledgeMap_top`} type="primary" onClick={this.newKnowledge}>{getLabel(82, '新建')}</Button>,
    ]}

    render() {
        const { KnowledgeMapListStore } = this.props;
        const { _top, content, height, locationkey, menu, menu1, topName, heightInit, isshowleft } = this.state;
        const { loading, slidevisible, hasRight } = KnowledgeMapListStore;
        let header = document.getElementsByClassName('e9theme-layout-header')[0] || document.getElementsByClassName('e9theme-layout2-navbar')[0] || document.getElementsByClassName('e8theme-layout-header')[0];
        if (header && !heightInit) {
            this.setState({ _top: this.getTopHeight(header), height: this.getHeight(header), heightInit: true });
        }
        return (
            <div className="knowledge-knowledgeMap-list">
                <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@lawyod`}
                    title={<span style={{ color: '#333333' }}>{getLabel(27939, '知识地图') + getLabel(320, '维护')}</span>}
                    icon={<i className="icon-coms-doc" />}
                    iconBgcolor="#FFB555"
                    buttons={this.getTopBtns()}
                    showDropIcon={true}
                    dropMenuDatas={menu}
                />
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@n86uvb`} datas={menu} showUrlItem={false} style={{ height: '100%' }}>
                    <div onClick={e => this.hideDetail(e)} style={{ height }}>
                        <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@87r408`} />
                        <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@4o3a77`} spinning={loading}>
                            <SearchCondition ecId={`${this && this.props && this.props.ecId || ''}_SearchCondition@66il79`} showSearchAd={'none'}
                                buttonsAd={this.getTabButtonsAd()}
                                leftItems={this.getLeftItems()}
                                locationkey={locationkey}
                                darkHeight={height - 105}
                                scrollHeight={375}
                            />

                            {this.getDetail()}
                        </Spin>
                    </div>
                </WeaRightMenu>
                <WeaSlideModal ecId={`${this && this.props && this.props.ecId || ''}_WeaSlideModal@cpxewh`} visible={slidevisible}
                    width={75}
                    height={100}
                    top={_top}
                    direction={'right'}
                    measure={'%'}
                    measureT={'px'}
                    content={(content)}
                    onClose={this.onCloseSlideModal}
                />
            </div>
        );
    }
}
